package com.guosen.zebra.framework.starter.sms.internal;

import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.basic.http.OKHttpClientUtil;
import com.guosen.zebra.framework.starter.sms.exception.SmsException;
import com.guosen.zebra.framework.starter.sms.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * SMS http 客户端
 */
@Slf4j
public class SmsHttpClient {

    private SmsHttpClient() {}

    /**
     * http协议客户端
     */
    private static final OkHttpClient HTTP_CLIENT = OKHttpClientUtil.getHttpClient();

    /**
     * https客户端，忽略证书
     */
    private static final OkHttpClient UNSAFE_HTTPS_CLIENT = OKHttpClientUtil.getUnsafeHttpsClient();

    public static JsonNode post(String url, Map<String, String> formData)
            throws SmsException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        for(Map.Entry<String, String> parameter : formData.entrySet())
            formBodyBuilder.add(parameter.getKey(), parameter.getValue());
        Request request = buildRequest(url, formBodyBuilder.build());
        return doInvoke(request, url);
    }

    private static Request buildRequest(String url, FormBody formBody) {
        try {
            return new Request.Builder().url(url).post(formBody).build();
        } catch (Exception e) {
            log.error("Failed to resolve url: {}, error message : {}", url, e.getMessage(), e);
            throw new SmsException("请求url解析异常！", e);
        }
    }

    private static JsonNode doInvoke(Request request, String url) throws SmsException {
        JsonNode result = null;
        try (Response response = getHttpClient(url).newCall(request).execute();
             ResponseBody responseBody = response.body()) {
            if (responseBody != null) {
                String respString = responseBody.string();
                if (StringUtils.isNotBlank(respString)) {
                    result = JsonUtil.getObjectMapper().readTree(respString);
                }
            }
        } catch (Exception e) {
            log.error("Failed to invoke {}, error message : {}", url, e.getMessage(), e);
            throw new SmsException("500", e.getMessage());
        }

        return result;
    }

    private static OkHttpClient getHttpClient(String url) {
        boolean isHttps = StringUtils.startsWithIgnoreCase(url, "https");
        return isHttps ? UNSAFE_HTTPS_CLIENT : HTTP_CLIENT;
    }
}
